﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Collections;
using Entities = GMAC.ReportingSystem.Business.Entities;
using System.Data;
using Components = GMAC.ReportingSystem.Business.Components;
using FrameworkManapro.Utilities;

namespace GMAC.ReportingSystem.Paginas
{
    public partial class CallingIVR : System.Web.UI.Page
    {
        #region Page Events

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!User.Identity.IsAuthenticated || Session["User"] == null)
            {
                System.Web.Security.FormsAuthentication.RedirectToLoginPage();
                return;
            }
            if (IsPostBack) return;
            Initialize();
            ValidateSecurity();

        }

        #endregion

        #region Button Events

        protected void btnNew_Click(object sender, ImageClickEventArgs e)
        {
            try
            {
                var frc = new Components.CallingIVRComponent();
                var CallingIVR = ReadCallingIVR();
                CallingIVR.ID = frc.Create(CallingIVR);
                var audit = new FrameworkManapro.Audit.Audit<Entities.CallingIVR>
                {
                    EntityKey = CallingIVR.ID.ToString(),
                    EventDate = DateTime.Now,
                    EventType = FrameworkManapro.Audit.AuditEvent.Insert,
                    NewObject = CallingIVR,
                    UserId = ((Entities.User)Session["User"]).UserID
                };
                var auditDAC = new FrameworkManapro.Audit.AuditDataAccess<Entities.CallingIVR>(audit);
                auditDAC.InsertAudit();
                wucMessage.ShowMessage(UserControls.MessageType.Success, "The Calling IVR was successfully saved.", null);
                popupExtenderMessage.Show();
                this.PagingControl.TotalRecords = Search();
                Search();

                ClearFields();
            }
            catch (Exception ex)
            {
                FrameworkManapro.ErrorHandling.LoggingError.PostErrorEventViewer(ex.Message, "New Calling IVR", "btnNew_Click", System.Diagnostics.TraceEventType.Error, ex.StackTrace);
                wucMessage.ShowMessage(UserControls.MessageType.Error, "The Calling IVR could not be saved", null);
                popupExtenderMessage.Show();
            }
        }
        protected void btnSave_Click(object sender, ImageClickEventArgs e)
        {
            btnSave.Visible = false;
            btnNew.Visible = true;
            var frc = new Components.CallingIVRComponent();
            try
            {
                var CallingIVR = ReadCallingIVR();
                if (hfID.Value.Trim() != string.Empty)
                {
                    CallingIVR.ID = int.Parse(hfID.Value);
                    var oldCallingIVR = frc.GetDetails(CallingIVR.ID);
                    frc.Edit(CallingIVR);
                    var audit = new FrameworkManapro.Audit.Audit<Entities.CallingIVR>
                    {
                        EntityKey = CallingIVR.ID.ToString(),
                        EventDate = DateTime.Now,
                        EventType = FrameworkManapro.Audit.AuditEvent.Update,
                        OldObject = oldCallingIVR,
                        NewObject = CallingIVR,
                        UserId = ((Entities.User)Session["User"]).UserID
                    };
                    var auditDAC = new FrameworkManapro.Audit.AuditDataAccess<Entities.CallingIVR>(audit);
                    auditDAC.InsertAudit();
                    wucMessage.ShowMessage(UserControls.MessageType.Success, "The CallingIVR was successfully saved.", null);
                    popupExtenderMessage.Show();
                    this.PagingControl.TotalRecords = Search();
                    Search();
                    ClearFields();
                }
            }
            catch (Exception ex)
            {
                FrameworkManapro.ErrorHandling.LoggingError.PostErrorEventViewer(ex.Message, "Save CallingIVR", "btnSave_Click", System.Diagnostics.TraceEventType.Error, ex.StackTrace);
                wucMessage.ShowMessage(UserControls.MessageType.Error, "The CallingIVR couldn't be saved.", null);
                popupExtenderMessage.Show();
            }
        }
        protected void btnCancel_Click(object sender, ImageClickEventArgs e)
        {
            btnSave.Visible = false;
            btnNew.Visible = true;
            ClearFields();
        }
        protected void btnModify_Click(object sender, ImageClickEventArgs e)
        {
            if (grvCallingIVRs != null)
            {
                if (grvCallingIVRs.SelectedDataKey != null)
                {
                    try
                    {
                        var CallingIVRId = (int)this.grvCallingIVRs.SelectedDataKey.Value;
                        var frc = new Components.CallingIVRComponent();
                        var CallingIVR = frc.GetDetails(CallingIVRId);
                        hfID.Value = CallingIVRId.ToString();
                        txtCalls.Text = CallingIVR.Calls.ToString();
                        txtDate.Text = CallingIVR.DateCall.ToString();
                        btnSave.Visible = true;
                        btnNew.Visible = false;
                    }
                    catch (Exception ex)
                    {
                        FrameworkManapro.ErrorHandling.LoggingError.PostErrorEventViewer(ex.Message, "Modify Calling IVR", "btnModify_Click", System.Diagnostics.TraceEventType.Error, ex.StackTrace);
                        wucMessage.ShowMessage(UserControls.MessageType.Error, "An error has occurred changing the CallingIVR.", ex.ToString());
                        popupExtenderMessage.Show();
                    }
                }
                else
                {
                    wucMessage.ShowMessage(UserControls.MessageType.Information, "A Calling IVR must be selected.", null);
                    popupExtenderMessage.Show();
                }
            }
        }
        protected void btnDelete_Click(object sender, ImageClickEventArgs e)
        {
            if (grvCallingIVRs.SelectedDataKey != null)
            {
                popupExtenderConfirm.Show();
            }
            else
            {
                wucMessage.ShowMessage(UserControls.MessageType.Information, "A Calling IVR must be selected.", null);
                popupExtenderMessage.Show();
            }
        }
        protected void btnConfirm_Click(object sender, ImageClickEventArgs e)
        {
            try
            {
                var frc = new Components.CallingIVRComponent();
                if (grvCallingIVRs.SelectedDataKey != null)
                {
                    var CallingIVRId = (int)this.grvCallingIVRs.SelectedDataKey.Value;
                    var CallingIVR = new Entities.CallingIVR { ID = CallingIVRId };
                    var oldCallingIVR = frc.GetDetails(CallingIVR.ID);
                    frc.Delete(CallingIVR);
                    var audit = new FrameworkManapro.Audit.Audit<Entities.CallingIVR>
                    {
                        EntityKey = CallingIVR.ID.ToString(),
                        EventDate = DateTime.Now,
                        EventType = FrameworkManapro.Audit.AuditEvent.Delete,
                        OldObject = oldCallingIVR,
                        UserId = ((Entities.User)Session["User"]).UserID
                    };
                    var auditDAC = new FrameworkManapro.Audit.AuditDataAccess<Entities.CallingIVR>(audit);
                    auditDAC.InsertAudit();
                    this.PagingControl.TotalRecords = Search();
                    Search();
                    wucMessage.ShowMessage(UserControls.MessageType.Success, "The Calling IVR was successfully deleted.", null);
                    popupExtenderMessage.Show();
                }
            }
            catch (Exception ex)
            {
                FrameworkManapro.ErrorHandling.LoggingError.PostErrorEventViewer(ex.Message, "Delete Calling IVR", "btnConfirm_Click", System.Diagnostics.TraceEventType.Error, ex.StackTrace);
                wucMessage.ShowMessage(UserControls.MessageType.Error, "The CallingIVR couldn't be deleted.", ex.ToString());
                popupExtenderMessage.Show();
            }

        }
        protected void imgBuscarReg_Click(object sender, ImageClickEventArgs e)
        {
            this.PagingControl.TotalRecords = Search();
            Search();
            if (this.PagingControl.TotalRecords == 0)
            {
                PagingControl.Visible = false;
            }
            else
            {
                PagingControl.Visible = true;
            }
            ClearFields();
        }

        #endregion

        #region Other Events

        protected void grvCallingIVRs_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                e.Row.Attributes["OnClick"] = ClientScript.GetPostBackEventReference(grvCallingIVRs, "Select$" + e.Row.RowIndex);
                
            }
        }

        #endregion

        #region Private Methods

        private void ClearFields()
        {
            txtCalls.Text = string.Empty;
            txtDate.Text = string.Empty;
            txtDateSearch.Text = string.Empty;
            hfID.Value = string.Empty;

        }
        private void Initialize()
        {
            try
            {
                //OJO esto tiene que llenarse dese la base de datos
               
                btnSave.Visible = false;
                btnNew.Visible = true;
                wucMessageConfirm.ShowMessage(UserControls.MessageType.Information,
                                              "Are you sure you want to delete the selected Calling IVR?", null);
                this.PagingControl.TotalRecords = Search();
                Search();
            }
            catch (Exception ex)
            {
                FrameworkManapro.ErrorHandling.LoggingError.PostErrorEventViewer(ex.Message, "Initialize page", "Initialize", System.Diagnostics.TraceEventType.Error, ex.StackTrace);
                wucMessage.ShowMessage(UserControls.MessageType.Error, "An error occurred initializing the page.", ex.ToString());
                popupExtenderMessage.Show();
            }

        }
        private void ValidateSecurity()
        {
            var beEntities = ((Entities.User)Session["User"]).Role.Security.GetEntitySecurity("CallingIVR");
            if (beEntities == null) return;
            if (!beEntities.CanRead)
            {
                grvCallingIVRs.Visible = false;
                btnModify.Visible = false;
                btnDelete.Visible = false;
                pnlSearch.Visible = false;
            }
            if (!beEntities.CanWrite)
            {
                btnSave.Visible = false;
            }
            if (!beEntities.CanInsert)
            {
                btnNew.Visible = false;
                btnCancel.Visible = false;
                pnlEdit.Visible = false;
            }
            if (!beEntities.CanDelete)
            {
                btnDelete.Visible = false;
            }
        }
        private int Search()
        {
            try
            {
                var bc = new Components.CallingIVRComponent();
                DateTime? DateCalls = null;
                if (!string.IsNullOrEmpty(txtDateSearch.Text))
                    DateCalls = DateTime.Parse(txtDateSearch.Text);
              
                FrameworkManapro.WebUI.PagingDetails paging = new FrameworkManapro.WebUI.PagingDetails();
                paging.PageNumber = this.PagingControl.PageNumber;
                paging.PageSize = this.PagingControl.PageSize;
                paging.SortBy = this.PagingControl.SortExpression;
                paging.SortDirection = this.PagingControl.SortDirection;



                Entities.CallingIVRCollection CallingIVRcollection = bc.Search(DateCalls, paging);

                grvCallingIVRs.DataSource = CallingIVRcollection;
                grvCallingIVRs.DataBind();
                return CallingIVRcollection.TotalResults;
            }
            catch (Exception ex)
            {
                FrameworkManapro.ErrorHandling.LoggingError.PostErrorEventViewer(ex.Message, "Search Calling IVR", "void Search", System.Diagnostics.TraceEventType.Error, ex.StackTrace);
                wucMessage.ShowMessage(UserControls.MessageType.Error, "An error has occurred during the search.", ex.ToString());
                popupExtenderMessage.Show();
                return 0;

            }
        }
        private Entities.CallingIVR ReadCallingIVR()
        {
            var CallingIVR = new Entities.CallingIVR
            {
                
                DateCall = DateTime.Parse(txtDate.Text),
                Calls = int.Parse(txtCalls.Text)
            };
            if (!string.IsNullOrEmpty(hfID.Value))
            {
                CallingIVR.ID = Convert.ToInt32(hfID.Value);
            }


            return CallingIVR;
        }
        protected void pagingControl_PageChanged(object sender, EventArgs e)
        {
            Search();
        }
        #endregion

        private DataTable GenerateDataTablePrueba()
        {
            DataTable dt = new DataTable();
            dt.Columns.Add("DateCall", typeof(string));
            dt.Columns.Add("Calls", typeof(string));
            DataRow rowdt;
            rowdt = dt.NewRow();
            rowdt[0] = "04/03/2011";
            rowdt[1] = "50";
            dt.Rows.Add(rowdt);

            rowdt = dt.NewRow();
            rowdt[0] = "05/03/2011";
            rowdt[1] = "67";
            dt.Rows.Add(rowdt);

            return dt;

        }
    }
}
